package com.isyscore.cse.sdk.test

import com.isyscore.cse.sdk.CrossScriptEngine
import org.junit.Test
import java.io.File
import kotlin.concurrent.thread

const val SCRIPT_PAS = """#language pascal

var
  dd: TDeviceDot;
  b: boolean;
  iParam: string;
  iBool: string;
begin
  setIiosIdptHost('10.20.3.174', 39104);
  dd := findDeviceDot('1', '1');
  iParam := dd._param;
  // print(dd._param);

  dd._pk := '123'; 
  b := assignDeviceDot(dd);
  iBool := boolToStr(b);
  // print(boolToStr(b));
  dd.Free;
end.
"""

const val SCRIPT_JS = """#language javascript

{
    setIiosIdptHost("10.20.3.174", 39104);
    var dd = findDeviceDot("1", "1");
    var iParam = TDeviceDot(dd)._param;
    print(iParam);
    TDeviceDot(dd)._param = "123";
    var b = assignDeviceDot(dd);
    var iBool = boolToStr(b);
    print(iBool);
    TDeviceDot(dd).Free;
}
"""

const val SCRIPT_CPP = """#language cpp

{
    setIiosIdptHost("10.20.3.174", 39104);
    TDeviceDot dd = findDeviceDot("1", "1");
    string iParam = dd._param;
    print(iParam);
    dd._param = "123";
    bool b = assignDeviceDot(dd);
    string iBool = boolToStr(b);
    print(iBool);
    dd.Free;
}
"""

class TestScript {

    @Volatile
    var running = true

    @Test
    fun test() {
        CrossScriptEngine.initSDK()
        // 直接以代码形式解释执行
        val sid = CrossScriptEngine.addScriptText(SCRIPT_CPP)
        CrossScriptEngine.setExecuteTimeout(sid, 20000L)
        val b = CrossScriptEngine.runScript(sid)
        if (!b) {
            val err = CrossScriptEngine.getErrorMessage(sid)
            println(err)
        } else {
            val outmsg = CrossScriptEngine.getOutputMessage(sid)
            println(outmsg)
        }
        CrossScriptEngine.removeScript(sid)
    }

    @Test
    fun testWithCompile() {
        CrossScriptEngine.initSDK()
        thread {
            // 文件落盘才能编译
            val fCode = File("./main.txt").apply { writeText(SCRIPT_PAS) }
            val sid = CrossScriptEngine.addScriptFile(fCode.absolutePath)
            CrossScriptEngine.setExecuteTimeout(sid, 20000L)
            var (b, path) = CrossScriptEngine.compile(sid)
            if (b) {
                b = CrossScriptEngine.runScript(sid)
                if (b) {
                    println("output: ${CrossScriptEngine.getOutputMessage(sid)}")
                } else {
                    println("run error: ${CrossScriptEngine.getErrorMessage(sid)}")
                }
            } else {
                println("compile error: ${CrossScriptEngine.getErrorMessage(sid)}")
            }
            CrossScriptEngine.removeScript(sid)
            running = false
        }
        while (running) {

        }
    }

}